package com.ywyself.ext.kit;

import java.util.Map;
import java.util.Map.Entry;

/**
 *
 * @author YuWenYue
 * @date 2017年11月6日 下午7:20:38
 */
public class JoinSql {

    /**
     * 拼接更新的sql语句
     * 
     * @param id
     *            主键值
     * @param tableName
     *            表名
     * @param data
     *            数据
     * @return 拼接好的sql语句
     */
    public static String joinUpdate(long id, String tableName, Map<String, Object> data) {
        StringBuffer sb = new StringBuffer("UPDATE ").append(tableName);
        boolean isFirst = true;
        if (data != null && data.size() > 0) {
            for (Entry<String, Object> d : data.entrySet()) {
                if (isFirst) {
                    isFirst = false;
                    sb.append(" SET");
                } else {
                    sb.append(",");
                }
                sb.append(" `").append(d.getKey()).append("` = '").append(d.getValue()).append("'");
            }
        }
        sb.append(" WHERE id = ").append(id);
        return sb.toString();
    }

    /**
     * 拼接查询语句
     * 
     * @param select
     *            为null则查询所有， 查询的参数，字段=别名，别名可以为null
     * @param tableName
     *            表名
     * @param cond
     *            为空则表示无条件， 条件，条件=值,多条件之间只有and连接
     * @return
     */
    public static String joinSelect(Map<String, String> select, String tableName, Map<String, Object> cond) {
        StringBuffer sb = new StringBuffer("SELECT ");
        if (select == null || select.size() == 0) {
            sb.append("*");
        } else {
            boolean isFirstSel = true;
            for (Entry<String, String> entry : select.entrySet()) {
                if (isFirstSel) {
                    isFirstSel = false;
                    sb.append("");
                } else {
                    sb.append(", ");
                }
                sb.append(entry.getKey());
                if (entry.getValue() != null && entry.getValue().trim() != "") {
                    sb.append(" AS ").append(entry.getValue());
                }
            }
        }
        sb.append(" FROM ").append(tableName);
        boolean isFirstCond = true;
        if (cond != null && cond.size() > 0) {
            for (Entry<String, Object> d : cond.entrySet()) {
                if (isFirstCond) {
                    isFirstCond = false;
                    sb.append(" WHERE ");
                } else {
                    sb.append(" AND ");
                }
                sb.append(d.getKey()).append(" = '").append(d.getKey());
            }
        }
        return sb.toString();
    }

}
